#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "ai_test.h"
#include "ai_rw.h"
#include "ai_config.h"
#include "unit_test.h"
#include "thread_ctrl.h"
#include "ietAiLib.h"

static struct unit_item_t unit_item[AI_ITEM_NUM];
static struct thread_param_t thread_param[AI_MAX_NUM];
static struct thread_info_t thread_info = {
    .num = AI_MAX_NUM,
    .param = thread_param,
};
static struct ai_dev_t ai_dev[AI_MAX_NUM];
struct ai_param_t ai_param = {
    .dev = ai_dev,
};
static struct ai_item_t ai_item = {
    .param = &ai_param,
    .thread = &thread_info,
};

static void init_unit_item(struct unit_item_t *item) {
    item[0] = (struct unit_item_t){0,  "null",          "0. 退出程序",        NULL};
    item[1] = (struct unit_item_t){1,  "ai_samp",       "1. 连续采集, 滑窗滤波, 不发中断",                 config_ai_mode_sample};
    item[2] = (struct unit_item_t){2,  "ai_samp_tim",   "2. 连续采集, 定时(抽样滑窗数据)触发PCIe中断",      config_ai_mode_sample_time_irq};
    item[3] = (struct unit_item_t){3,  "ai_raw_dma",    "3. 连续采集, 原始数据, 发DMA中断",                config_ai_mode_raw_dma_irq};
    item[4] = (struct unit_item_t){4,  "ai_waw",        "4. 连续采集, 原始数据, 不发中断",                 config_ai_mode_raw};
}

static int get_param(struct ai_param_t *param) {
    struct ai_item_t *punit = (struct ai_item_t *)param->parent;
    struct thread_info_t *pthread_info = punit->thread;
    struct thread_param_t *pthread = pthread_info->param;
    int ret = 0;
    char input[32];
    uint8_t i = 0;

    printf("\n===== %s 设备测试程序 =====\n", AI_ITEM_NAME);
    printf("请选择测试项:\n");
    for (int i = 0; i < AI_ITEM_NUM; i++) {
        printf("%s\n", unit_item[i].text);
    }
    printf("请输入选择 (输入数字): ");
    if (fgets(input, sizeof(input), stdin) == NULL) {
        return -1;
    }
    if (pthread->exit_sig) {
        param->item_id = 0;
        return 0;
    }
    param->item_id = atoi(input);
    if (param->item_id == 0)
        return 0;
    if (unit_item[param->item_id].config != NULL) {
        unit_item[param->item_id].config(param);
    }

    if (param->item_id == 1 || param->item_id == 4) {
        printf("请输入%s通道号 (0-%d): ", AI_ITEM_NAME, param->max_num - 1);
        if (fgets(input, sizeof(input), stdin) == NULL) {
            return -1;
        }
        if (pthread->exit_sig) {
            param->item_id = 0;
            return 0;
        }
        input[strcspn(input, "\n")] = '\0';
        if (strlen(input) == 0) {
            param->dev_id = param->max_num;
        } else {
            param->dev_id = atoi(input);
        }
        if (param->dev_id >= param->max_num) {
            param->dev_id = 0;
            for (i = 0; i < param->max_num; i++) {
                param->dev[i].index = i;
            }
        } else {
            param->dev_num = 1;
            param->dev[param->dev_id].index = param->dev_id;
        }

        printf("请输入电压/电流类型 (0/1): ");
        if (fgets(input, sizeof(input), stdin) == NULL) {
            return -1;
        }
        if (pthread->exit_sig) {
            param->item_id = 0;
            return 0;
        }
        param->val_type = atoi(input);
    } else {
        param->dev_id = 0;
        param->dev_num = 1;
        param->dev[param->dev_id].index = param->dev_id;
    }

    return ret;
}

int ai_test(int argc, char *argv[])
{
    struct thread_param_t *pthread = &thread_param[0];
    struct ai_param_t *pparam = &ai_param;
    struct ai_dev_t *pdev= &pparam->dev[0];
    int ret = 0;
    uint8_t i = 0;
    uint8_t thread_cnt = 0;
    pthread_t sig_tid;

    ai_item.thread = &thread_info;
    ai_item.thread->param = &thread_param[0];
    ai_item.param = &ai_param;
    ai_item.param->dev_num = AI_MAX_NUM;
    ai_item.param->dev = &ai_dev[0];
    ai_param.parent = &ai_item;
    for (i = 0; i < AI_MAX_NUM; i++) {
        ai_dev[i].parent = (void *)ai_item.param;
    }

    init_process_signal_handle(&sig_tid, signal_handler_thread, ai_item.thread);
    init_unit_item(unit_item);

    while (!pthread->exit_sig) {
        if (get_module_type(&pparam->type) < 0) {
            printf("无效选择，请重新输入\n");
            sleep(2);
            continue;
        } else {
            break;
        }
    }
    pparam->dev_num = get_dev_num(AI_DRV_NAME);
    pparam->max_num = pparam->dev_num;
    printf("Get %s device number %d\n", AI_DRV_NAME, pparam->dev_num);
    while (!pthread->exit_sig) {
        thread_cnt = 0;
        // ai_param.dev_num = AI_MAX_NUM;

        if (argc > 2) {
            for(i = 0; i < argc; i++) {
                printf("%s ", argv[i]);
            };
            printf("\n");
            return EXIT_FAILURE;
        }else {
            if (0 != get_param(pparam)) {
                printf("无效选择，请重新输入\n");
                continue;
            }
            if (0 == pparam->item_id) {
                printf("程序退出\n");
                break;
            }
        }

        if (unit_item[pparam->item_id].config != NULL) {
            printf("\n测试项 %d 正在执行\n", pparam->item_id);
            ret = AIMOpen(pparam->type);
            if (ret < 0) {
                fprintf(stderr, "Open AI device failed\n");
                return ret;
            }
            printf("AIMGetDrvVer v%d.%d\n", ((AIMGetDrvVer() >> 8) & 0xFF), (AIMGetDrvVer() & 0xFF));
            printf("AIMGetFpgaVer v%d.%d\n", ((AIMGetFpgaVer() >> 8) & 0xFF), (AIMGetFpgaVer() & 0xFF));
            printf("AIMGetLibVer v%d.%d\n", ((AIMGetLibVer() >> 8) & 0xFF), (AIMGetLibVer() & 0xFF));
            for (i = pparam->dev_id; i < (pparam->dev_id + pparam->dev_num); i++) {
                pdev = &pparam->dev[i];
                if (pparam->en_read == 1) {
                    pdev->read_thread = &pthread[thread_cnt];
                    snprintf(pthread[thread_cnt].name, sizeof(pthread[thread_cnt].name), "%s%s%d", "recv_", pparam->name, pdev->index);
                    if (pthread_create(&pthread[thread_cnt].id, NULL, recv_ai_thread, pdev) != 0) {
                        fprintf(stderr, "Create %s receive thread failed\n", pdev->path);
                    } else {
                        // printf("Create %s receive thread success\n", pdev->path);
                    }
                    thread_cnt++;
                    usleep(5000);
                }
            }
            for (i = 0; i < thread_cnt && !pthread->exit_sig; i++) {
                pthread_join(pthread[i].id, NULL);
            }
            AIMClose();

            if (pthread->exit_sig) {
                printf("测试项 %d 用户取消\n", pparam->item_id);
            } else {
                printf("测试项 %d 执行完成\n", pparam->item_id);
            }
        } else {
            printf("测试项 %d 尚未实现\n", pparam->item_id);
            sleep(2);
        }

        thread_cnt = 0;
    }

    printf("%s return\n", __func__);

    return ret;
}
